//
//  SubmitOrderViewController.m
//  YYPHSpeedJump
//
//  Created by sujiang on 15/12/30.
//  Copyright © 2015年 sujiang. All rights reserved.
//

#import "SubmitOrderViewController.h"
#import "Order.h"
#import <AlipaySDK/AlipaySDK.h>
#import "DataSigner.h"
#import "AddressManager.h"
#import "PayResultVC.h"
#import "BuyerModel.h"


@interface SubmitOrderViewController ()<UIAlertViewDelegate>
{
    NSTimer *timer;
    NSInteger remain_wait_seconds;
    NSTimer *requestTimer;
}

@property (nonatomic, assign) BOOL isYE;
@property (nonatomic, assign) BOOL isZFB;
@property (nonatomic, assign) BOOL isWX;
@property (nonatomic, assign) NSInteger remainTime;
@property (weak, nonatomic) IBOutlet UIImageView *selectYEImageView;
@property (weak, nonatomic) IBOutlet UIImageView *selectZFBImageView;

@end

@implementation SubmitOrderViewController
- (void)viewWillAppear:(BOOL)animated

{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidAppear:(BOOL)animated
{
    requestTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(actionRequest) userInfo:nil repeats:YES];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [timer invalidate];
    [requestTimer invalidate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _isYE = YES;
    _isZFB = NO;
    _isWX = NO;
    self.waitingNumberLabel.hidden = YES;
    self.selectYEImageView.hidden = NO;
    self.selectZFBImageView.hidden = YES;
    if (self.pushType.integerValue == 1) {
        [self setUpdataTypeOne];
    } else {
      [self setUpdataTypeO];
    }
    self.title = @"订单详情";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AliPayResultNotify:) name:@"Alipay" object:nil];
}

- (void)setUpdataTypeOne
{
    self.goodNameLb.text = self.sendModel.name;
    [self.goodPic sd_setImageWithURL:[NSURL URLWithString:self.sendModel.head_img_url] placeholderImage:[UIImage imageNamed:@"tu-xiao"]];
    self.priceLb.text = self.sendModel.buy_price;
    self.creatOrderId = self.sendModel.deal_id;
    self.leftTimeLb.text = self.sendModel.remain_seconds;
    self.remainTime = self.sendModel.remain_seconds.integerValue;
    remain_wait_seconds = self.sendModel.remain_wait_seconds.integerValue;
    [self handleWithLeftTime];
    self.addressLb.text = self.sendModel.address;
    self.phoneNum.text = self.sendModel.phone;
    self.name.text = self.sendModel.real_name;
    self.period_id = self.sendModel.period_id;
    [NSThread detachNewThreadSelector:@selector(startTimer) toTarget:self withObject:nil];
    if (self.addressLb.text == nil) {
        [Tools showAlert:@"请添加收货地址"];
        self.nextStepBtn.userInteractionEnabled = NO;
        return;
    }
}

- (void)setUpdataTypeO
{
    NSLog(@"ZYTest --- %@",self.dataDic);
    NSDictionary *buy_result = self.dataDic[@"buy_result"];    
    //NSDictionary *default_address = self.dataDic[@"default_address"];
    self.goodNameLb.text = buy_result[@"name"];
    self.goodPic.image = self.goodImage;
    self.priceLb.text = buy_result[@"buy_price"];
    self.creatOrderId = buy_result[@"deal_id"];
    self.leftTimeLb.text = buy_result[@"remain_seconds"];
    // self.period_id = buy_result[@"period_id"];
    self.remainTime = [buy_result[@"remain_seconds"] integerValue];
    remain_wait_seconds = [buy_result[@"remain_wait_seconds"] integerValue];
    [self handleWithLeftTime];
    [NSThread detachNewThreadSelector:@selector(startTimer) toTarget:self withObject:nil];
//    if (default_address == nil) {
//        [Tools showAlert:@"请添加收货地址"];
//        self.nextStepBtn.userInteractionEnabled = NO;
//        return;
//    }
    if ([self.dataDic[@"default_address"] isKindOfClass:[NSString class]]) {
        
    }else{
    NSDictionary *default_address = self.dataDic[@"default_address"];
        if (default_address == nil) {
            [Tools showAlert:@"请添加收货地址"];
            self.nextStepBtn.userInteractionEnabled = NO;
            return;
        }
    self.addressLb.text = default_address[@"address"];
    self.phoneNum.text = default_address[@"phone"];
    self.name.text = default_address[@"real_name"];
    }
}

- (void)startTimer
{
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] run];
}

- (void)timerRun
{
    if (remain_wait_seconds > 0) {
        self.waitingNumberLabel.hidden = NO;
        self.currentStatusLable.text = @"排队中";
        self.remainTime = remain_wait_seconds;
        remain_wait_seconds -= 1.0f;
        
        return;
    } else {
        self.waitingNumberLabel.hidden = YES;
        self.currentStatusLable.text = @"支付中";
        self.remainTime = self.leftTimeLb.text.integerValue;
    }
    if (self.remainTime <= 0) {
        self.remainTime = 0;
        [timer invalidate];
        return;
    }
    self.remainTime -= 1.0f;
}

- (void)setRemainTime:(NSInteger)remainTime
{
    _remainTime = remainTime;
    [self performSelectorOnMainThread:@selector(handleWithLeftTime) withObject:nil waitUntilDone:YES];
}

- (void)handleWithLeftTime
{
    if (remain_wait_seconds > 0) {
        NSInteger waitingNumb = remain_wait_seconds/60;
        NSInteger surplusS = remain_wait_seconds%60;
        NSString *waitingNumberStr = nil;
        if (waitingNumb==0) {
            waitingNumberStr = [NSString stringWithFormat:@"(您之前有1人,排队时间%lds)",surplusS];
        }else{
            waitingNumberStr = [NSString stringWithFormat:@"(您之前有%ld人,排队时间%ldm%lds)",waitingNumb+1,waitingNumb,surplusS];
        }
        self.waitingNumberLabel.text = waitingNumberStr;
        self.nextStepBtn.userInteractionEnabled = NO;
        [self.nextStepBtn setBackgroundImage:nil forState:(UIControlStateNormal)];
        [self.nextStepBtn setTitle:[NSString stringWithFormat:@"%lds",remain_wait_seconds] forState:(UIControlStateNormal)];
        [self.nextStepBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        self.nextStepBtn.backgroundColor = kColors(159, 159, 159, 1);
        self.nextStepBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    } else {
        if (self.period_id != nil) {
            [self actionRequest];
        }
        [self.nextStepBtn setTitle:@"下一步" forState:(UIControlStateNormal)];
        self.nextStepBtn.userInteractionEnabled = YES;
        self.nextStepBtn.backgroundColor =kColors(218, 166, 46, 1);
        self.nextStepBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        [self.nextStepBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        self.leftTimeLb.text = [NSString stringWithFormat:@"%ld", _remainTime];
    }
    
}


#pragma mark -- 按钮点击事件

- (IBAction)actionYEPay:(id)sender {
    // 选择余额支付
    self.remainPayBtn = sender;
    self.isYE = YES;
    self.isWX = !self.isYE;
    self.isZFB = !self.isYE;
    self.selectYEImageView.hidden = NO;
    self.selectZFBImageView.hidden = YES;
    // [self.wxPayBtn setBackgroundImage:[UIImage imageNamed:@"wxzf"] forState:(UIControlStateNormal)];
    //[self.zfbPayBtn setBackgroundImage:[UIImage imageNamed:@"zfbzf"] forState:(UIControlStateNormal)];
    //[self.remainPayBtn setBackgroundImage:[UIImage imageNamed:@"yezfz"] forState:(UIControlStateNormal)];
    
}


//- (IBAction)actionWXPay:(id)sender {
//    // 选择微信支付
//    self.wxPayBtn = sender;
//    self.isWX = YES;
//    self.isZFB = !self.isWX;
//    self.isYE = !self.isWX;
//    [self.wxPayBtn setBackgroundImage:[UIImage imageNamed:@"wxzfxz"] forState:(UIControlStateNormal)];
//    [self.zfbPayBtn setBackgroundImage:[UIImage imageNamed:@"zfbzf"] forState:(UIControlStateNormal)];
//    [self.remainPayBtn setBackgroundImage:[UIImage imageNamed:@"yrzf"] forState:(UIControlStateNormal)];
//}

- (IBAction)actionZFBPay:(id)sender {
    // 选择支付宝支付
    self.zfbPayBtn = sender;
    self.isZFB = YES;
    self.isWX = !self.isZFB;
    self.isYE = !self.isZFB;
    self.selectYEImageView.hidden = YES;
    self.selectZFBImageView.hidden = NO;
   // [self.zfbPayBtn setBackgroundImage:[UIImage imageNamed:@"zfbzfxz"] forState:(UIControlStateNormal)];
   // [self.wxPayBtn setBackgroundImage:[UIImage imageNamed:@"wxzf"] forState:(UIControlStateNormal)];
    //[self.remainPayBtn setBackgroundImage:[UIImage imageNamed:@"yrzf"] forState:(UIControlStateNormal)];
}

- (IBAction)actionChangeAddress:(id)sender {
    // 更改收货地址
    AddressManager *addrVC = [[AddressManager alloc] init];
    [self.navigationController pushViewController:addrVC animated:YES];
    addrVC.deal_id = self.creatOrderId;
    addrVC.changeAddr = ^(AddressModel *model){
        self.nextStepBtn.userInteractionEnabled = YES;
        self.addressLb.text = model.address;
        self.phoneNum.text = model.phone;
        self.name.text = model.real_name;
    };
    
}


- (IBAction)actionNextStep:(id)sender {
    // 下一步
    if (self.isZFB) {
        // 跳转支付宝
        [self zhifubaoMethod];
    } else if (self.isWX) {
        // 跳转微信
        [[WXPayManager shareManager] wxpay];
    } else if (self.isYE) {
        // 余额支付
       // &u=39&deal_id=2016011215493039191909&period_id=1909&price=777.9
        NSString *string = [NSString stringWithFormat:@"%@%@", kBaseUrl, kYEPayUrl];
        NSDictionary *dict = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"deal_id":self.creatOrderId, @"period_id":self.period_id, @"price":self.priceLb.text};
        [NetworkHandle getInfoWithUrl:string dictionary:dict success:^(NSDictionary *dictionary) {
            NSLog(@"%@", dictionary);
            PayResultVC *resultVC = [[PayResultVC alloc] initWithNibName:@"PayResultVC" bundle:nil];
            resultVC.dictionary = [NSDictionary dictionaryWithDictionary:dictionary];
            [self.navigationController pushViewController:resultVC animated:YES];
        }];
        
    }
    
    
}


//支付宝
-(void)zhifubaoMethod
{
    // 支付2, 充值1
    [[ZFBPayManager shareManager] alipayWithOrderProductName:@"速降支付" notifyUrl:kPayNotifyUrl productDescription:@"速降商品支付" money:self.priceLb.text paymentType:@"2" tradeNO:self.creatOrderId];

}

-(void)AliPayResultNotify:(NSNotification *)notify
{
    NSDictionary *dict = [notify userInfo];
    [self AliPayResult:dict];
}

#pragma mark    ----支付宝回调结果结果判断-----
-(void)AliPayResult:(NSDictionary *)resultDic
{
    /*
     9000 订单支付成功
     8000 正在处理中
     4000 订单支付失败
     6001 用户中途取消
     6002 网络连接出错
     */
    NSLog(@"result = %@", resultDic[@"resultStatus"]);
    NSDictionary *stateDict = @{@"9000":@"订单支付成功",@"8000":@"正在处理中",@"4000":@"订单支付失败",@"6001":@"用户中途取消",@"6002":@"网络连接出错"};
    
    if([resultDic[@"resultStatus"] isEqualToString:@"9000"]){//支付成功
        //支付成功返回上一页
        __weak typeof(SubmitOrderViewController *)myself = self;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            
            [myself.navigationController popViewControllerAnimated:YES];
            // [myself.navigationController popToRootViewControllerAnimated:YES];
        });
        
    }else {
        NSString *msg = [stateDict valueForKey:resultDic[@"resultStatus"]];
        [self alert:@"提示" msg:msg];
    }
    
}

//客户端提示信息
- (void)alert:(NSString *)title msg:(NSString *)msg
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alter show];
}

- (void)alertView:(nonnull UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([alertView.message isEqualToString:@"支付成功"] ||[alertView.message isEqualToString:@"支付结果：成功！"]) {
        PayResultVC *resultVC = [[PayResultVC alloc] initWithNibName:@"PayResultVC" bundle:nil];
        [self.navigationController pushViewController:resultVC animated:YES];
    }
    if (alertView.tag == 111) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

- (void)actionRequest
{
    if (self.period_id != nil) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSString *url = [NSString stringWithFormat:@"%@%@", kBaseUrl, @"/user.do?cmd=current_period_buy_list"];
        NSDictionary *diction = @{@"period_id":self.period_id};
        NSMutableDictionary *signDict = [NSMutableDictionary dictionaryWithDictionary:diction];
        [signDict setValue:[Tools signDict:diction] forKey:@"sign"];
        [manager POST:url parameters:signDict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            NSDictionary *dict = responseObject;
            NSDictionary *dictionary = dict[@"data"];
            NSArray *array = dictionary[@"list"];
            for (NSDictionary *dic in array) {
                BuyerModel *model = [[BuyerModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                if (model.status.integerValue == 3 && ![model.user_id isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"]]) {
                    [requestTimer invalidate];
                    [timer invalidate];
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已有用户支付成功,点击确认返回!" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                    alert.tag = 111;
                    [alert show];
                    return;
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@", error);
        }];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
